package HibernateOrederManagement.app;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import HibernateOrderManagerment.bean.Goods;
import HibernateOrderManagerment.bean.GoodsStatus;
import HibernateOrderManagerment.bean.Store;
import HibernateOrderManagerment.bean.StoreGoods;

public class StoreGoodsDao {
private Session session;
	
	public StoreGoodsDao(Session session){
		this.session=session;
	}
	
	public List<StoreGoods> list(){
		Query<StoreGoods> query=session.createQuery("from StoreGoods",StoreGoods.class);
		
		return query.getResultList();
	}
	
	public StoreGoods getStoreGoodsById(long id){
		return session.get(StoreGoods.class,id);
	}
	
	public StoreGoods getByCode(int price){
		Query<StoreGoods> query =session.createQuery("from StoreGoods where price=:price",StoreGoods.class);
		query.setParameter("price", price);
		return query.getSingleResult();
	}
	public StoreGoods getByStoreId(long id){
		StoreDao dao =new StoreDao(session);
		Store store =dao.getStoreById(id);
		Query<StoreGoods> query =session.createQuery("from StoreGoods where store=:store",StoreGoods.class);
		query.setParameter("store", store);
		return query.getSingleResult();
	}
	public StoreGoods getByGoodsId(long id){
		GoodsDao dao =new GoodsDao(session);
		Goods goods =dao.getGoodsById(id);
		Query<StoreGoods> query =session.createQuery("from StoreGoods where goods=:goods",StoreGoods.class);
		query.setParameter("goods", goods);
		return query.getSingleResult();
	}
	public StoreGoods getByGoodsStatus(long id){
		GoodsStatusDao dao =new GoodsStatusDao(session);
		GoodsStatus goodsStatus =dao.getGoodsStatusById(id);
		Query<StoreGoods> query =session.createQuery("from StoreGoods where goodsStatus=:goodsStatus",StoreGoods.class);
		query.setParameter("goodsStatus", goodsStatus);
		return query.getSingleResult();
	}
	
	public void insert(StoreGoods storeGoods) {
		Transaction tx = session.beginTransaction();
		try {

			session.save(storeGoods);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	public void update(StoreGoods storeGoods){
		Transaction tx = session.beginTransaction();
		try {

			session.update(storeGoods);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}
	public void delete(StoreGoods storeGoods){
		Transaction tx = session.beginTransaction();
		try {
			
			session.delete(storeGoods);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}

}
